package org.example.ai04.security;

import org.example.ai04.entity.User;
import org.example.ai04.repository.UserRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

/**
 * 自定义用户详情服务
 * 实现Spring Security的UserDetailsService接口
 * 用于加载用户信息，支持身份验证
 */
@Service
public class CustomUserDetailsService implements UserDetailsService {

    // 注入用户存储库，用于访问用户数据
    @Autowired
    private UserRepository userRepository;

    /**
     * 根据用户名加载用户详情
     * 用于Spring Security的身份验证过程
     * @param username 用户名
     * @return UserDetails对象，包含用户的认证信息和权限
     * @throws UsernameNotFoundException 当用户不存在时抛出
     */
    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        // 从数据库中查找用户，如果不存在则抛出异常
        User user = userRepository.findByUsername(username)
                .orElseThrow(() -> new UsernameNotFoundException("用户不存在: " + username));
        // 将用户实体转换为UserDetails对象返回
        return new CustomUserDetails(user);
    }
}